package org.caowei.samples.sevice;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.caowei.samples.dao.FUserSubjectDAO;
import org.caowei.samples.dao.IExamScoreDAO;
import org.caowei.samples.model.ExamScore;
import org.caowei.samples.model.Subject;
import org.caowei.samples.model.UserSubject;
import org.caowei.samples.vo.ExamScoreVO;
import org.caowei.samples.vo.SubjectVO;
import org.caowei.samples.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class StudentService implements IStudentService {

	@Autowired
	private FUserSubjectDAO fUserSubjectDAO;
	
	@Autowired
	private IExamScoreDAO examScoreDAO;
	
	@Override
	public List<SubjectVO> getSubjectList(UserVO uservo){
		List<SubjectVO> resultList = new ArrayList<SubjectVO>();
		//读取所有科目
//		User user = iUserDAO.get(uservo.getUserId());
//		Collection<Subject> subs = user.getExamSubjects();
		List<UserSubject> ulist = fUserSubjectDAO.findAll();
		List<Subject> subs = new ArrayList<Subject>();
		for(UserSubject a : ulist){
			if(a.getUser().getUserId().equals(uservo.getUserId())){
				subs.add(a.getSubject());
			}
		}
		for(Subject sub : subs){
			SubjectVO subVO = new SubjectVO();
			BeanUtils.copyProperties(sub, subVO);
			//读取对应科目的成绩
			ExamScore score = examScoreDAO.getScore(uservo.getUserId(),subVO.getSubId());
			if(score != null){
				ExamScoreVO scoreVO = new ExamScoreVO();
				BeanUtils.copyProperties(score, scoreVO);
				//计算剩余考试时间
				Calendar startTime = Calendar.getInstance();
				startTime.setTime(scoreVO.getExamTime());
				Calendar currentTime = Calendar.getInstance();
				currentTime.setTime(new Date());
				long startSecond = startTime.getTimeInMillis();
				long currentSecond = currentTime.getTimeInMillis();
				long totalSecond = sub.getTotalTime() * 60;
				scoreVO.setRemainingExamTime(totalSecond - (currentSecond - startSecond) / 100);
				subVO.setScore(scoreVO);
			}
			resultList.add(subVO);
		}
		return resultList;
	}
	
	@Override
	public ExamScoreVO getScoreById(Integer scoreId){
		ExamScoreVO vo = examScoreDAO.getScoreById(scoreId);
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		vo.setExamTimeString(df.format(vo.getExamTime()));
		return vo;
	}

	@Override
	public ExamScoreVO calculateScore(List<Integer> answerIds, Map<String, String[]> testMap, String userId,
			Integer subId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public SubjectVO getSubjectById(Integer subId) {
		// TODO Auto-generated method stub
		return null;
	}
	
}
